<template>
  <div v-show="currentView === 'performance'" class="space-y-6">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-4">
      <h2 class="text-2xl font-bold">绩效管理</h2>
      <div class="flex space-x-3 mt-4 md:mt-0">
        <div class="relative">
          <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索员工..."
            class="pl-9 pr-4 py-2 rounded-lg border border-light-1 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all duration-200"
          />
          <i class="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-dark-3"></i>
        </div>
        <select
          v-model="selectedPeriod"
          class="px-4 py-2 rounded-lg border border-light-1 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all duration-200"
        >
          <option value="currentMonth">本月</option>
          <option value="lastMonth">上月</option>
          <option value="currentQuarter">本季度</option>
          <option value="lastQuarter">上季度</option>
          <option value="currentYear">本年</option>
        </select>
      </div>
    </div>

    <!-- 绩效概览卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-dark-2 font-medium">平均绩效</h3>
          <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa-solid fa-star"></i>
          </div>
        </div>
        <div class="text-3xl font-bold mb-2">{{ averagePerformance }}</div>
        <div class="text-success text-sm flex items-center">
          <i class="fa-solid fa-arrow-up mr-1"></i> {{ averagePerformance }}% <span class="text-dark-3 ml-1">较上月</span>
        </div>
      </div>

      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-dark-2 font-medium">最高绩效</h3>
          <div class="w-10 h-10 rounded-full bg-success/10 flex items-center justify-center text-success">
            <i class="fa-solid fa-trophy"></i>
          </div>
        </div>
        <div class="text-3xl font-bold mb-2">{{ highestPerformance.score }}</div>
        <div class="text-sm text-dark-3">
          <span class="font-medium">{{ highestPerformance.name }}</span> - {{ highestPerformance.department }}
        </div>
      </div>

      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-dark-2 font-medium">最低绩效</h3>
          <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning">
            <i class="fa-solid fa-exclamation-circle"></i>
          </div>
        </div>
        <div class="text-3xl font-bold mb-2">{{ lowestPerformance.score }}</div>
        <div class="text-sm text-dark-3">
          <span class="font-medium">{{ lowestPerformance.name }}</span> - {{ lowestPerformance.department }}
        </div>
      </div>

      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-dark-2 font-medium">绩效达标率</h3>
          <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary">
            <i class="fa-solid fa-check-circle"></i>
          </div>
        </div>
        <div class="text-3xl font-bold mb-2">{{ complianceRate }}%</div>
        <div class="text-success text-sm flex items-center">
          <i class="fa-solid fa-arrow-up mr-1"></i> {{ complianceRate }}% <span class="text-dark-3 ml-1">较上月</span>
        </div>
      </div>
    </div>

    <!-- 绩效趋势图 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-6">
          <h3 class="font-bold text-lg">部门绩效对比</h3>
          <button class="text-dark-3 hover:text-primary">
            <i class="fa-solid fa-ellipsis-v"></i>
          </button>
        </div>
        <div class="h-80">
          <canvas ref="departmentChartRef"></canvas>
        </div>
      </div>

      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-6">
          <h3 class="font-bold text-lg">个人绩效分布</h3>
          <button class="text-dark-3 hover:text-primary">
            <i class="fa-solid fa-ellipsis-v"></i>
          </button>
        </div>
        <div class="h-80">
          <canvas ref="distributionChartRef"></canvas>
        </div>
      </div>
    </div>

    <!-- 员工绩效表格 -->
    <div class="bg-white rounded-xl shadow-card overflow-hidden">
      <div class="p-5 border-b border-light-1 flex items-center justify-between">
        <h3 class="font-bold text-lg">员工绩效排名</h3>
        <div class="flex space-x-2">
          <button @click="filterByDepartment('all')" class="px-3 py-1 text-xs bg-primary text-white rounded-lg">全部部门</button>
          <button @click="filterByDepartment('production')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            生产部
          </button>
          <button @click="filterByDepartment('quality')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            质检部
          </button>
          <button @click="filterByDepartment('material')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            物料部
          </button>
          <button @click="filterByDepartment('technology')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            技术部
          </button>
        </div>
      </div>
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="bg-light-2">
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">排名</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">员工姓名</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">部门</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">职位</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">绩效评分</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">工单完成率</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">质量合格率</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-light-1">
            <tr
              v-for="(employee, index) in filteredEmployees"
              :key="employee.id"
              class="hover:bg-light-2/50 transition-colors duration-150"
            >
              <td class="px-5 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div
                    :class="{
                      'w-6 h-6 rounded-full bg-primary text-white flex items-center justify-center text-xs font-bold':
                        index === 0,
                      'w-6 h-6 rounded-full bg-dark-3 text-white flex items-center justify-center text-xs font-bold': index > 0
                    }"
                  >
                    {{ index + 1 }}
                  </div>
                </div>
              </td>
              <td class="px-5 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <img :src="employee.avatar" alt="用户头像" class="w-7 h-7 rounded-full mr-2" />
                  <span class="text-sm font-medium">{{ employee.name }}</span>
                </div>
              </td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">{{ employee.department }}</td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">{{ employee.position }}</td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">
                <span :class="getScoreClass(employee.score)" class="font-bold">{{ employee.score }}</span>
              </td>
              <td class="px-5 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <span class="text-sm mr-2">{{ employee.workOrderCompletionRate }}%</span>
                  <div class="w-20 h-1.5 bg-light-2 rounded-full overflow-hidden">
                    <div
                      :class="{
                        'h-full bg-success rounded-full': employee.workOrderCompletionRate >= 90,
                        'h-full bg-warning rounded-full':
                          employee.workOrderCompletionRate >= 70 && employee.workOrderCompletionRate < 90,
                        'h-full bg-danger rounded-full': employee.workOrderCompletionRate < 70
                      }"
                      :style="{ width: `${employee.workOrderCompletionRate}%` }"
                    ></div>
                  </div>
                </div>
              </td>
              <td class="px-5 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <span class="text-sm mr-2">{{ employee.qualityPassRate }}%</span>
                  <div class="w-20 h-1.5 bg-light-2 rounded-full overflow-hidden">
                    <div
                      :class="{
                        'h-full bg-success rounded-full': employee.qualityPassRate >= 90,
                        'h-full bg-warning rounded-full': employee.qualityPassRate >= 70 && employee.qualityPassRate < 90,
                        'h-full bg-danger rounded-full': employee.qualityPassRate < 70
                      }"
                      :style="{ width: `${employee.qualityPassRate}%` }"
                    ></div>
                  </div>
                </div>
              </td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">
                <button @click="viewEmployeeDetails(employee.id)" class="text-primary hover:text-primary/80">详情</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="p-5 border-t border-light-1 flex items-center justify-between">
        <div class="text-sm text-dark-3">
          显示 1 到 {{ Math.min(filteredEmployees.length, pageSize) }} 条，共 {{ employees.length }} 条
        </div>
        <div class="flex space-x-1">
          <button
            @click="prevPage"
            class="w-8 h-8 flex items-center justify-center rounded-lg border border-light-1 text-dark-3 hover:bg-light-1"
          >
            <i class="fa-solid fa-angle-left"></i>
          </button>
          <button
            v-for="page in totalPages"
            :key="page"
            :class="{
              'w-8 h-8 flex items-center justify-center rounded-lg bg-primary text-white': page === currentPage,
              'w-8 h-8 flex items-center justify-center rounded-lg border border-light-1 hover:bg-light-1': page !== currentPage
            }"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
          <button
            @click="nextPage"
            class="w-8 h-8 flex items-center justify-center rounded-lg border border-light-1 text-dark-3 hover:bg-light-1"
          >
            <i class="fa-solid fa-angle-right"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { Chart } from "chart.js";

// 部门映射
const DEPARTMENTS = {
  production: "生产部",
  quality: "质检部",
  material: "物料部",
  technology: "技术部"
};

// 状态管理
const currentView = ref("performance");
const searchQuery = ref("");
const selectedPeriod = ref("currentMonth");
const currentDepartmentFilter = ref("all");
const currentPage = ref(1);
const pageSize = ref(3);

// 数据
const employees = ref([
  {
    id: 1,
    name: "李四",
    department: "生产部",
    departmentKey: "production",
    position: "组长",
    score: 98.7,
    workOrderCompletionRate: 99,
    qualityPassRate: 98,
    avatar: "https://picsum.photos/id/1027/32/32"
  },
  {
    id: 2,
    name: "张三",
    department: "生产部",
    departmentKey: "production",
    position: "工人",
    score: 95.3,
    workOrderCompletionRate: 97,
    qualityPassRate: 96,
    avatar: "https://picsum.photos/id/1012/32/32"
  },
  {
    id: 3,
    name: "赵六",
    department: "质检部",
    departmentKey: "quality",
    position: "主管",
    score: 94.1,
    workOrderCompletionRate: 98,
    qualityPassRate: 99,
    avatar: "https://picsum.photos/id/1066/32/32"
  }
  // 更多员工数据...
]);

// 计算属性
const filteredEmployees = computed(() => {
  let filtered = employees.value;

  // 按部门过滤
  if (currentDepartmentFilter.value !== "all") {
    filtered = filtered.filter(employee => employee.departmentKey === currentDepartmentFilter.value);
  }

  // 按搜索词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(
      employee =>
        employee.name.toLowerCase().includes(query) ||
        employee.department.toLowerCase().includes(query) ||
        employee.position.toLowerCase().includes(query)
    );
  }

  // 排序
  filtered.sort((a, b) => b.score - a.score);

  return filtered;
});

const totalPages = computed(() => {
  return Math.ceil(filteredEmployees.value.length / pageSize.value);
});

const averagePerformance = computed(() => {
  if (employees.value.length === 0) return 0;
  const sum = employees.value.reduce((total, employee) => total + employee.score, 0);
  return (sum / employees.value.length).toFixed(1);
});

const highestPerformance = computed(() => {
  if (employees.value.length === 0) return { name: "", department: "", score: 0 };
  return employees.value.reduce((highest, employee) => (employee.score > highest.score ? employee : highest), {
    name: "",
    department: "",
    score: 0
  });
});

const lowestPerformance = computed(() => {
  if (employees.value.length === 0) return { name: "", department: "", score: 0 };
  return employees.value.reduce((lowest, employee) => (employee.score < lowest.score ? employee : lowest), {
    name: "",
    department: "",
    score: 100
  });
});

const complianceRate = computed(() => {
  if (employees.value.length === 0) return 0;
  const compliantCount = employees.value.filter(employee => employee.score >= 90).length;
  return Math.round((compliantCount / employees.value.length) * 100);
});

// 图表相关
const departmentChartRef = ref(null);
const distributionChartRef = ref(null);
let departmentChart = null;
let distributionChart = null;

// 生命周期钩子
onMounted(() => {
  initCharts();
});

onUnmounted(() => {
  if (departmentChart) {
    departmentChart.destroy();
    departmentChart = null;
  }

  if (distributionChart) {
    distributionChart.destroy();
    distributionChart = null;
  }
});

// 方法
const initCharts = () => {
  initDepartmentChart();
  initDistributionChart();
};

const initDepartmentChart = () => {
  if (!departmentChartRef.value) return;

  const ctx = departmentChartRef.value.getContext("2d");

  // 计算各部门平均绩效
  const departments = ["production", "quality", "material", "technology"];
  const labels = departments.map(key => DEPARTMENTS[key]);
  const data = departments.map(key => {
    const deptEmployees = employees.value.filter(e => e.departmentKey === key);
    if (deptEmployees.length === 0) return 0;
    return deptEmployees.reduce((total, e) => total + e.score, 0) / deptEmployees.length;
  });

  departmentChart = new Chart(ctx, {
    type: "bar",
    data: {
      labels: labels,
      datasets: [
        {
          label: "平均绩效",
          data: data,
          backgroundColor: [
            "rgba(59, 130, 246, 0.7)",
            "rgba(16, 185, 129, 0.7)",
            "rgba(245, 158, 11, 0.7)",
            "rgba(139, 92, 246, 0.7)"
          ],
          borderColor: ["rgb(59, 130, 246)", "rgb(16, 185, 129)", "rgb(245, 158, 11)", "rgb(139, 92, 246)"],
          borderWidth: 1
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: true,
          max: 100,
          grid: {
            drawBorder: false
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      }
    }
  });
};

const initDistributionChart = () => {
  if (!distributionChartRef.value) return;

  const ctx = distributionChartRef.value.getContext("2d");

  // 计算绩效分布
  const distribution = {
    "优秀(90-100)": 0,
    "良好(80-89)": 0,
    "合格(70-79)": 0,
    "不合格(<70)": 0
  };

  employees.value.forEach(employee => {
    if (employee.score >= 90) {
      distribution["优秀(90-100)"]++;
    } else if (employee.score >= 80) {
      distribution["良好(80-89)"]++;
    } else if (employee.score >= 70) {
      distribution["合格(70-79)"]++;
    } else {
      distribution["不合格(<70)"]++;
    }
  });

  const labels = Object.keys(distribution);
  const data = Object.values(distribution);

  distributionChart = new Chart(ctx, {
    type: "doughnut",
    data: {
      labels: labels,
      datasets: [
        {
          data: data,
          backgroundColor: [
            "rgba(16, 185, 129, 0.7)",
            "rgba(59, 130, 246, 0.7)",
            "rgba(245, 158, 11, 0.7)",
            "rgba(239, 68, 68, 0.7)"
          ],
          borderColor: ["rgb(16, 185, 129)", "rgb(59, 130, 246)", "rgb(245, 158, 11)", "rgb(239, 68, 68)"],
          borderWidth: 1
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "right"
        }
      }
    }
  });
};

const filterByDepartment = department => {
  currentDepartmentFilter.value = department;
  currentPage.value = 1; // 重置页码
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

const goToPage = page => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
  }
};

const getScoreClass = score => {
  if (score >= 90) {
    return "text-success";
  } else if (score >= 80) {
    return "text-primary";
  } else if (score >= 70) {
    return "text-warning";
  } else {
    return "text-danger";
  }
};

const viewEmployeeDetails = id => {
  console.log("查看员工详情:", id);
  // 实现查看员工详情逻辑
};

// 监听数据变化，更新图表
watch(employees, () => {
  if (departmentChart) {
    departmentChart.destroy();
  }

  if (distributionChart) {
    distributionChart.destroy();
  }

  initCharts();
});
</script>
